package com.chatgpt_backend.service.impl;

import com.chatgpt_backend.entity.chat.ServerChat;
import com.chatgpt_backend.mapper.UserMapper;
import com.chatgpt_backend.service.ChatService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

@Service
public class ChatServiceImpl implements ChatService {
    private static final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890));

    @Resource
    UserMapper userMapper;
    @Override
    public BufferedReader getReader(ServerChat<Object> serverChat, String key) throws Exception {
        HttpURLConnection connection = (HttpURLConnection) new URL("https://api.openai.com/v1/chat/completions").openConnection(proxy);
        connection.setRequestMethod("POST");
        connection.addRequestProperty("Content-Type", "application/json");
        connection.addRequestProperty("Authorization", "Bearer "+key);
        connection.setDoOutput(true);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
        writer.write(serverChat.toString());
        writer.close();
        return new BufferedReader(new InputStreamReader(connection.getInputStream()));
    }

    @Override
    public Integer getAccountIdByUsername(String username) {
        return userMapper.getAccountIdByUsername(username);
    }
}
